﻿using System;
using System.Web;
using System.Linq;
using Matrix_network.Code;

namespace Matrix_network.HttpHandlers
{
    public class PhotoHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        
        private MatrixDataClassesDataContext _dataContext = new MatrixDataClassesDataContext();

        private const int urlSegmentsCount = 3;
        private const int urlIdSegment = 2;
        private const string jpegContentType = "image/jpeg";

        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var response = context.Response;

            if (context.Request.Url.Segments.Length == urlSegmentsCount)
            {
                try
                {
                    int photoId;
                    if (!int.TryParse(context.Request.Url.Segments[urlIdSegment], out photoId))
                        throw new Exception("Photo id not set");

                    var data = _dataContext.photos.First(item => item.id == photoId).photo.ToArray();

                    response.ContentType = jpegContentType;
                    response.OutputStream.Write(data, 0, data.Length);
                    response.OutputStream.Close();
                }
                catch
                {
                    response.StatusCode = 404;
                    response.OutputStream.Close();
                }
            }
        }

        #endregion
    }
}
